package com.sfac.javaSpringBoot.modules.test.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sfac.javaSpringBoot.modules.common.entity.Result;
import com.sfac.javaSpringBoot.modules.common.entity.SearchBean;
import com.sfac.javaSpringBoot.modules.test.dao.CityDao;
import com.sfac.javaSpringBoot.modules.test.entity.City;
import com.sfac.javaSpringBoot.modules.test.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityDao cityDao;
    @Override
    @Transactional
    public Result<City> insertCity(City city) {
        city.setDateCreated(new Date());
        cityDao.insertCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,"insert success",city);
    }

    @Override
    @Transactional
    public Result<City> updateCity(City city) {
        cityDao.updateCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,"update success",city);
    }

    @Override
    @Transactional
    public Result<Object> deleteCity(int cityId) {
        cityDao.deleteCity(cityId);
        return new Result<>(Result.ResultCode.SUCCESS.code,"delete success");
    }

    @Override
    public City getCityByCityId(int cityId) {
        return cityDao.getCityByCityId(cityId);
    }

    @Override
    public List<City> getCitiesByCountryId(int countryId) {
        return Optional
                .ofNullable(cityDao.getCitiesByCountryId(countryId))
                .orElse(Collections.emptyList());
    }

    @Override
    public PageInfo<City> getCitiesBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getCurrentPage(),searchBean.getPageSize());
        return new PageInfo<>((Optional.ofNullable(cityDao.getCitiesBySearchBean(searchBean)))
                .orElse(Collections.emptyList()));

    }

    @Override
    public Result<Object> insertCities(List<City> cities) {
        cities.stream().forEach(item->{
            item.setDateCreated(new Date());
        });
        cityDao.insertCities(cities);
        return new Result<>(Result.ResultCode.SUCCESS.code,"insert success");
    }
}
